﻿<?php
/*
**************************************************************************
*  File: include/class_functions.php
*  (c) Extreme Portal Light Version 2012-2014
*  By elwizard & MGS Team. All rights reserved.
*  http://www.mgsteam.es
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
**************************************************************************
*/

if (!defined("IN_WEB")) {
    die ("Sorry !! You cannot access this file directly.");
}


class ext {
	
	var $sitepath = "";
	var $siteurl = "";
	var $adminpath = "";
	var $template = "";
	var $images = "";
	var $lang = "";
	var $mainsite = "";
	var $config = array();
	var $perms = array();
 	
 	###########################################################  WEB #####################################################
 	// Header para la web
	function header() {
		global $tpl;
		 
		// read stylesheet
  	$stylesheet = "<link href=\"templates/default/style.css\" type=\"text/css\" rel=\"stylesheet\" />
  	               <link href=\"templates/default/navbar.css\" type=\"text/css\" rel=\"stylesheet\" />
  	               ";
    
    // read AJAX code  	
  	$AJAX = "<script src=\"ajax.js\" type=\"text/javascript\"></script>
  	          <script src=\"basic.js\" type=\"text/javascript\"></script>";
	  
		// read header
	  $output = $tpl->header($stylesheet, $AJAX);
 	
  	// start main
    $output .= $tpl->open_main();
	    
    // read logo
    $output .= $tpl->view_logo();
	  
	  // read body
	  $output .= $tpl->open_body();
	   
	  
	  return $output;
	}
		
	function footer() {
		global $tpl;
    
    //close body
		$output = $tpl->close_body();
		
		$output .= $tpl->close_main();
		
		$output .= $tpl->footer();
		
		return $output;
	}
	 
	// THIS FUNCTION LOADS A MODULE
	function printpage($title, $title2, $blocks) {
		global $tpl;
		
		//read header
		$output = $this->header();

		// read center column
		$output .= "<div style=\"text-align: center\">
		            <table cellpadding=\"0\" cellspacing=\"0\" style=\"width: 800px; margin-left: 40px; margin-right: 40px;\">";		
		$contenido = $tpl->get_contents($title, $title2, $blocks);
		$output .= $this->convert_ISO_to_UTF8($contenido);
		$output .= "</table></div>";

		$output .= $this->footer();
    // END WARNING
		
		print $output;
		//$salida2 = ob_get_contents();
    //ob_end_clean();
    //echo $salida2;
		exit;
	}
	
	// THIS FUNCTION LOADS THE INDEX WITH THE BLOCKS (CONTENT MODULE)
	function printpage_blocks($blocks) {
		global $tpl, $DB;
		
		//read header
		$output = $this->header();
		$output .= "<div style=\"text-align: center\">";
		$output .= "<table cellpadding=\"0\" cellspacing=\"1\" border=\"0\" width=\"100%\" style=\"text-align: center;\">
		            <tr>
		            ";
		
		// read left column
		$output .= $this->load_blocks('left');
		
		
		// read center column
		$output .= $this->load_blocks('center');
		
		$output .= "</tr></table>";
		$output .= "</div>";
		
		$output .= $this->footer();
    
		// $DB->close_db();
		echo $output;
		
		//$salida2 = ob_get_contents();
    //ob_end_clean();
    //echo $salida2;
		exit;
	}
	
	###########################################################  ADMIN #####################################################
	// Header para el admin
	function header_admin() {
		global $tpl, $global;
		 
		// read stylesheet
  	$stylesheet = "<link href=\"../{$global['admin_dir']}/templates/default/style.css\" type=\"text/css\" rel=\"stylesheet\" />
  	               ";
    
    // read AJAX code  	
  	$AJAX = "<script src=\"../includes/ajax.js\" type=\"text/javascript\"></script>
  	          <script src=\"../includes/basic.js\" type=\"text/javascript\"></script>";
	  
		// read header
	  $output = $tpl->header_admin($stylesheet, $AJAX);
 	
  	// start main
    $output .= $tpl->open_main_admin();
	    
    // read logo
    $output .= $tpl->view_logo_admin();
	  
	  // read body
	  $output .= $tpl->open_body_admin();
	   
	  
	  return $output;
	}
	
	// Footer admin
	function footer_admin() {
		global $tpl;
    
    //close body
		$output = $tpl->close_body_admin();
		
		$output .= $tpl->close_main_admin();
		
		$output .= $tpl->footer_admin();
		
		return $output;
	}
	 
	// THIS FUNCTION LOADS A ADMIN MODULE
	function printpage_admin($title, $title2, $blocks) {
		global $tpl;
		
		//read header
		$output = $this->header_admin();

		// read center column
		$output .= "<div style=\"text-align: center\">
		            <table cellpadding=\"0\" cellspacing=\"0\" style=\"width: 800px; margin-left: 40px; margin-right: 40px;\">";		
		$contenido = $tpl->get_contents($title, $title2, $blocks);
		$output .= $this->convert_ISO_to_UTF8($contenido);
		$output .= "</table></div>";

		$output .= $this->footer_admin();
    // END WARNING
		
		print $output;
		//$salida2 = ob_get_contents();
    //ob_end_clean();
    //echo $salida2;
		exit;
	}
	
	// THIS FUNCTION LOADS A ADMIN MODULE
	function printblocks_admin($title, $title2, $blocks) {
		global $tpl;
		
		//read header
		$output = $this->header_admin();

		// read columns
		$output .= "<div style=\"text-align: center\">";
		$output .= "<table cellpadding=\"0\" cellspacing=\"1\" border=\"0\" width=\"100%\" style=\"text-align: center;\">
		            <tr>
		            ";
		
		// read left column
		$output .= $this->load_blocks('left','admin');
		
		
		// read center column
		$output .= $this->load_blocks('center', 'admin_module', $title, $title2, $blocks);
		
		$output .= "</tr></table>";
		$output .= "</div>";
		
		//$output .= $this->convert_ISO_to_UTF8($contenido);

		$output .= $this->footer_admin();
    // END WARNING
		
		print $output;
		//$salida2 = ob_get_contents();
    //ob_end_clean();
    //echo $salida2;
		exit;
	}	
	
	################### SOLO LOGIN ADMIN #######################
	// Header para el admin
	function header_login_admin() {
		global $tpl, $global;
		 
		// read stylesheet
  	$stylesheet = "<link href=\"../{$global['admin_dir']}/templates/default/style.css\" type=\"text/css\" rel=\"stylesheet\" />";
    
    // read AJAX code  	
  	$AJAX = "<script src=\"../includes/ajax.js\" type=\"text/javascript\"></script>
  	         <script src=\"../includes/basic.js\" type=\"text/javascript\"></script>";
	  
		// read header
	  $output = $tpl->header_admin($stylesheet, $AJAX);
 	
  	// start main
    $output .= $tpl->open_main_admin();
	    
    // read logo
    $output .= $tpl->view_logo_admin_login();
	  
	  // read body
	  $output .= $tpl->open_body_admin();
	   
	  
	  return $output;
	}
	
	// Footer admin
	function footer_login_admin() {
		global $tpl;
    
    //close body
		$output = $tpl->close_body_admin();
		
		$output .= $tpl->close_main_admin();
		
		$output .= $tpl->footer_admin();
		
		return $output;
	}
	
	
	// THIS FUNCTION LOADS A ADMIN LOGIN MODULE
	function printpage_login_admin($title, $title2, $blocks) {
		global $tpl;
		
		//read header
		$output = $this->header_login_admin();

		// read center column
		$output .= "<div style=\"text-align: center\">
		            <table cellpadding=\"0\" cellspacing=\"0\" style=\"width: 800px; margin-left: 40px; margin-right: 40px;\">";		
		$contenido = $tpl->contents_login($title, $title2, $blocks);	
		$output .= $this->convert_ISO_to_UTF8($contenido);
		$output .= "</table></div>";

		$output .= $this->footer_login_admin();
    // END WARNING
		
		print $output;
		exit;
	}
	
	
	// THIS FUNCTION LOADS THE INDEX WITH THE BLOCKS (ADMIN)
	function printpage_blocks_admin() {
		global $tpl, $DB;
		
		//read header
		$output = $this->header_admin();
		$output .= "<div style=\"text-align: center\">";
		$output .= "<table cellpadding=\"0\" cellspacing=\"1\" border=\"0\" width=\"100%\" style=\"text-align: center;\">
		            <tr>
		            ";
		
		// read left column
		$output .= $this->load_blocks('left', 'admin');
		
		
		// read center column
		$output .= $this->load_blocks('center', 'admin');
		
		$output .= "</tr></table>";
		$output .= "</div>";
		
		$output .= $this->footer_admin();
    
		// $DB->close_db();
		echo $output;
		
		//$salida2 = ob_get_contents();
    //ob_end_clean();
    //echo $salida2;
		exit;
	}
	
  
  ############################################ COMMON FUNCTIONS ##############################################
  
  function load_blocks($place, $system='', $title='', $title2='', $content=''){
  	global $tpl, $DB, $db_prefix, $vbulletin;
  	
  	$block_location = "";
		$column = "";
		$block = array();
    
		// izq, der o centro?
		if ($place=="left") {
      $block_location .= "and blocation = '0' ";
    } elseif ($place=="right") {
      $block_location .= "and blocation = '2' ";
    } else {
    	$block_location .= "and blocation = '1' ";
    }
		
		// discriminamos si leemos bloques de admin o de la web
		if ($system=="admin") {
      $block_location .= "and bpersonal = '1'";
		} else {
		  $block_location .= "and bpersonal != '1'";
		}
  	
  	// Leemos los bloques
		$query = $DB->query("SELECT bid, bfile, bname, btitles, bicon, bposition, blocation, bactive, bpersonal, 
		                     bcontent, bperms, bcollapse, bno_title, bstyle, bview FROM {$db_prefix}blocks 
		                     WHERE bactive = '1' $block_location ORDER BY `bposition` ASC");
    while ($row = $DB->fetch_row($query)) {
    	$bid = intval($row['bid']);  
    	$block[$bid]['bid'] = $bid;                                                // ID del bloque
    	$block[$bid]['bname'] = $this->convert_ISO_to_UTF8(trim($row['bname']));   // nombre del bloque
    	$block[$bid]['btitles'] = $row['btitles'];                                 // idiomas
      $block[$bid]['bfile'] = trim($row['bfile']);                               // nombre del archivo
      $block[$bid]['bicon'] = trim($row['bicon']);                               // icono
      $block[$bid]['bposition'] = intval($row['bposition']);                     // orden de posición del bloque
      $block[$bid]['blocation'] = intval($row['blocation']);                     // situación 0 izq 1 cen 2 der
      $block[$bid]['bactive'] = intval($row['bactive']);                         // 0 no activo 1 activo
      $block[$bid]['bpersonal'] = intval($row['bpersonal']);                     // 0 web, 1 admin, 2 html, 3 php
      $block[$bid]['bcontent'] = trim($row['bcontent']);                         // bloque interno
      $block[$bid]['bperms'] = trim($row['bperms']);                             // permisos del bloque
      $block[$bid]['bcollapse'] = intval($row['bcollapse']);                     // disminuible (o colapsable?) 0 no 1 si
      $block[$bid]['bno_title'] = intval($row['bno_title']);                     // Sin titulo? 0 con título 1 sin título
      $block[$bid]['bstyle'] = trim($row['bstyle']);                             // Estilo del bloque
      $block[$bid]['bview'] = trim($row['bview']);                               // Forma del estilo del bloque
      
      // directorio del bloque
    	if ($system=="admin") {
    	  $block[$bid]['dir'] = "../blocks/acp/".$block[$bid]['bfile'];
    	} else {
 	      $block[$bid]['dir'] = "blocks/".$block[$bid]['bfile'];
 	      
 	    }
 	    
    } // end while 
    
    //echo "<br />".$block_location;
    //print_r($block);
    
    // OPCIONES IDIOMAS: Lenguage por referencia ó lenguage propio
    $def_lang = $this->config['default_lang'];
    $def_lang = $this->convert_ISO_to_UTF8($def_lang);        
    if ($def_lang == "") {
      $def_lang = "English (US)";
    }
    $my_lang = $vbulletin->session->vars['languageid'];
    $langcache = $vbulletin->languagecache;
    
    foreach ($langcache as $langs) {
	     $dlang = $langs['languageid'];
	     $mylangs[$dlang] = $this->convert_ISO_to_UTF8($langs['title']);
    }
    // Fin idiomas

    
    // Imprimimos un bloque / módulo admin?
    if ($system == "admin_module") {
    	
      $bid = "100";
      $column .= $tpl->view_module($title, $content, 'm'.$bid);
    
    // No, imprimimos fila de bloques
    } else {

      $column = "";
      
      if (is_array($block)) {
    
        $cbid = 0;
        foreach ($block as $file) {
        	$title = "";
        	
        	// Comprobamos si anulamos el título
          if (!$file['bno_title']) {
            $titlem = $file['btitles'];
            // convertimos los títulos de los bloques en una array
            $titlem = unserialize($titlem);
            $rel = array();
            
            // Limpiamos los títulos de los bloques de errores
            if (is_array($titlem)) {
			        foreach ($titlem as $k => $v) {
			          $v = $this->restore_quotes($v);
			          $v = $this->UTF8ToEntities($v);
			          $rel[$k] = $v;
			        }
			      }
            $titlem = $rel;

            // Seleccionamos traducción según idioma
            if (($my_lang != "") || ($my_lang != "0")) {
              $def_lang = $mylangs[$my_lang];
            }
            
            $title = $titlem[$def_lang];
            $title = $this->UTF8ToEntities($title);
            $title = $this->restore_quotes($title);
            if ($title=="null") { $title = ""; }
              
          }
    	
    	    $content = "";
          $titlem = "";
          $disablemoduleform = "";
    	
          if (is_file($file['dir'])) {
            require $file['dir'];
          }
          
          if ($content != "") {
          	
        	  if ($place == "center") {
        	
        	    if ($disablemoduleform) {
        	      $column .= $tpl->view_module_empty($title, $content);
        	    } else {
        	      $column .= $tpl->view_module($title, $content, 'm'.$cbid);
        	    }
            } else {
              $column .= $tpl->view_block($title, $content, $cbid);
            }
          
          }
          $cbid++;
        }
      }
    }
    
    // Situamos bloques en columnas
    if ($place=="left") {
      $blocks = $tpl->view_column_left($column);
    } elseif ($place=="right") {
      $blocks = $tpl->view_column_right($column);
    } else {
    	$blocks = $tpl->view_column_center($column);
    }
    
    // Nos olvidamos de los errores raros
    $blocks = $this->convert_ISO_to_UTF8($blocks);
    
    return $blocks;
	
	}
  
  
  function stimer() {
    global $Stime;
    $mtime = explode (' ', microtime ());
    $Stime = $mtime[1] + $mtime[0];
  }
	function etimer() {
    global $Stime;
    $mtime = explode (' ', microtime ());
    $endtime = $mtime[1] + $mtime[0];
    $ttime = round (($endtime - $Stime), 5);
    return $ttime;
  }
  
	
	// Creates a random password.
  function randomPass($length=10, $chrs = '1234567890qwertyuiopasdfghjklzxcvbnm') {
  	
    for($i = 0; $i < $length; $i++)
        $pwd .= $chrs{mt_rand(0, strlen($chrs)-1)};
    
    return $pwd;
    
  }
	
	function codepass($username, $pass, $salt) {
		
		if (empty($username) || empty($pass) || empty($salt))
		  return false;
		  
		return MD5($pass.$username.$salt);
	
	}
	 
  function checkpass($username, $pass, $salt) {
  	
	  if (empty($username) || empty($pass) || empty($salt))
		  return false;
		  
		  
	}
	
	function bantool($do) {
	
	  if ($do == "ban") {
	  	$rebel['warnedtype'] = "banned";
      $rebel = serialize($rebel);
      $rebel = base64_encode($rebel);
      @setcookie("premium", $rebel);
		}
	  
	  if ($do == "unban") {
	  	$rebel['warnedtype'] = "unbanned";
      $rebel = serialize($rebel);
      $rebel = base64_encode($rebel);
      @setcookie("premium", $rebel);
		}
		
		if ($do == "set") {
			$rebel['warnedtype'] = "";
      $rebel = serialize($rebel);
      $rebel = base64_encode($rebel);
      @setcookie("premium", $rebel);
		}
		
		if ($do == "read") {
			$rebel = $_COOKIE["premium"];
      $rebel = base64_decode($rebel);
      $rebel = unserialize($rebel);
		}
	  
	  return $rebel;
  }
  
  // Get the user ip
 	function get_ip() {
	  if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		  if(preg_match_all("#[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}#s", $_SERVER['HTTP_X_FORWARDED_FOR'], $addresses)) {
			  foreach($addresses[0] as $key => $val) {
				  if(!preg_match("#^(10|172\.16|192\.168)\.#", $val)) {
					  $ip = $val;
				 	  break;
				  }
			  }
		  }
	  }
	  
	  if(!isset($ip)) {
		  if(isset($_SERVER['HTTP_CLIENT_IP'])) {
			  $ip = $_SERVER['HTTP_CLIENT_IP'];
		  } else {
			  $ip = $_SERVER['REMOTE_ADDR'];
		  }
	  }
	  $ip = preg_replace("#([^.0-9 ]*)#", "", $ip);
	  return $ip;
  }
  
  function get_host($ip) {
    return gethostbyaddr($ip);
  }
  
  function get_agent() {
  	return $_SERVER['HTTP_USER_AGENT'];
  }
	
	function check_country() {
	   
	   // IP china 58.49.161.22 IP Rusa: 188.143.232.211   // Korea N. 175.45.176.0
	   
	   //$ip = $this->get_ip();
	   
	   $ipinfo['ip'] = "52.97.221.87";
	   $ip = $ipinfo['ip'];
     $ipinfo['host'] = $this->get_host($ipinfo['ip']);
	   $ipinfo['agent'] = $_SERVER['HTTP_USER_AGENT'];
	   $ipinfo['port'] = $_SERVER['REMOTE_PORT'];
	   
	   // Localizaci\u00F3n
     $data = array('host' => $ipinfo['ip']);
	   
	   $ch = curl_init();
	   curl_setopt($ch, CURLOPT_URL, "http://aruljohn.com/track.pl");  // Url a resolver
	   curl_setopt($ch, CURLOPT_HEADER, false);                        // Devolver HEADER
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 // Devolver datos en variable
	   curl_setopt($ch, CURLOPT_POST, true);                           // Enviar datos POST 
	   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);     // Datos post
	   
	   // Cogemos los datos de la web
	   $salida = curl_exec($ch);
	   
	   // Comprobamos si hay error
	   if(!curl_errno($ch)) {
       $info = curl_getinfo($ch);
 	     //print_r($info);
     } 
     curl_close($ch);
     
     // Buscamos datos
     
	   $salida1 = htmlentities($salida);
	   $pos1 = stripos($salida1, "Results of IP Tracking for");
	   $salida1 = substr($salida1, $pos1);
	   $pos2 = stripos($salida1, "Visual Map");
	   $salida1 = substr($salida1, 0, $pos2);
	   $pos3 = stripos($salida1, "ISP");
	   $salida1 = substr($salida1, $pos3+24);
	   $pos4 = stripos($salida1, "&lt;/td");
	   $ipinfo['isp'] = substr($salida1, 0, $pos4);
	   $pos5 = stripos($salida1, "Country&lt;/td&gt;");
	   $salida1 = substr($salida1, $pos5+28);
	   $pos6 = stripos($salida1, "&lt;img src");
	   $ipinfo['country'] = substr($salida1, 0, $pos6-1);
	   $pos7 = stripos($salida1, "/");
	   $salida1 = substr($salida1, $pos7);
	   $pos8 = stripos($salida1, "alt");
	   $ipinfo['fragurl'] = "http://aruljohn.com".substr($salida1, 0, $pos8-7);
	   
	   
	   /*
	   echo "IP: ".$ipinfo['ip']."<br />";
	   echo "HOST: ".$ipinfo['host']."<br />";
	   echo "AGENTE: ".$ipinfo['agent']."<br />";
	   echo "ISP: ".$ipinfo['isp']."<br />";
	   echo "PAIS: ".$ipinfo['country']."<br />";
	   echo "FLAG: <img src=".$ipinfo['fragurl']." alt=\"\" /><br />";
	   echo "PUERTO: ".$ipinfo['port']."<br />";
     echo "<br /><br />";
     */
	   
	   
	   return $ipinfo;
	}
	
	function proxie_running($ipinfo) {
	  
	   //http://www.all-nettools.com/toolbox/proxy-test.php?
	   $IS_PROXIE = 0;
	 
     
     if (preg_match("/anonymouse/i", $ipinfo['ip']))
       $IS_PROXIE = 1;
       
     if ($ipinfo['agent']== "http://Anonymouse.org/ (Unix)")
       $IS_PROXIE = 1;
     
     return $IS_PROXIE;
	}
	
	// Comprobamos si el usuario est\u00E1 baneado
	function check_banned($ipinfo) {
	  
	  
	  // mail82.anonymouse.org //Navegaci\u00F3n an\u00F3nima
	  $IS_BANNED = 0;
	  
	  // China ban
	  if ($ipinfo['country'] == "China")
	    $IS_BANNED = 1;
	  
	  // Rusia ban
	  if ($ipinfo['country'] == "Russian Federation")
	    $IS_BANNED = 1;
	    
	  // Nigeria ban
	  if ($ipinfo['country'] == "Nigeria")
	    $IS_BANNED = 1;
	  
	  // Nigeria ban
	  if ($ipinfo['country'] == "Korea, Democratic People's Republic")
	    $IS_BANNED = 1;
	  
	  return $IS_BANNED;
	}
	
	    
  function get_browser() {
   
    $agent = $this->get_agent();
    
    $browser['short'] = "UK";
    $browser['long'] = "Uknown";
    
    if (eregi("MSIE",$agent)) {
    	 
       $browser['short'] = "IE";
       $browser['long'] = "Internet Explorer";
    }

    if (eregi("Firefox",$agent)) {
       $browser['short'] = "FF";
       $browser['long'] = "Firefox"; 
    }
    
    if (eregi("Opera",$agent)) {
       $browser['short'] = "OP";
       $browser['long'] = "Opera Browser"; 
    }
    
    if (eregi("K-Meleon",$agent)) {
       $browser['short'] = "KM";
       $browser['long'] = "K-Meleon"; 
    }
    
    if (eregi("Safari",$agent)) {
       $browser['short'] = "SF";
       $browser['long'] = "Safari Browser"; 
    }
    
    if (eregi("Chrome",$agent)) {
       $browser['short'] = "GC";
       $browser['long'] = "Google Chrome Browser"; 
    }

    return $browser;
  
  }
  
  function convert_ISO_to_UTF8($v) {
    $v = preg_replace('/[^!-%\x27-;=?-~<>&\x09\x0a\x0d\x0B ]/e', '"&#".ord("$0").chr(59)', $v);
    $k = preg_replace('/Ã&#([0-9]+);/e', '"&#".((int) \\1 + 64).";"', $v);
    return $k;
  }
  
  // SEO options for Extreme Portal
  function friendly_urls() {
  	global $EXT_URL;
  	
    // Is this server an Apache one?
	  if (substr_count(php_sapi_name(), 'apache') < 1) {
	    return false;
	  }
	  
	  $URL = $_SERVER['REQUEST_URI'];
	  $act= "";
	  
	  //echo $URL;
	  
	  $pos = stripos("index.php", $URL);
	  $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
	  $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
	  $_SERVER['PATH_INFO'] = ""; // /contact 
	  $_SERVER['PATH_TRANSLATED'] = "";

	
	  // REQUEST_URI empty?
	  if (empty($URL)) 
	    return false;

	  $_GET = array(); // clear $_GET for no problems
	  	  
	  $REDIRECT = $_SERVER['QUERY_STRING'];
    $section = "";

    switch($REDIRECT) {
    	case 'banned':
	      $section = "banned";
        break;
      case 'contact':
	      $section = "services";
        break;
      case 'link_us':
	      $section = "services";
        break;
      case 'about_us':
	      $section = "mgsteam";
        break;
      case 'team_former':
	      $section = "mgsteam";
        break;
      case 'link_exchange':
	      $section = "mgsteam";
        break;
      case 'language-es':
	      $section = "language";
        break;
      case 'language-cat':
	      $section = "language";
        break;
      case 'language-en':
	      $section = "language";
        break;
      default:
        $section = "home";
        break;
    }
	  
	  return $section;	  
  }
  
  // SEO options for Extreme Portal (admin area)
  function friendly_urls_admin() {
  	global $EXT_URL;
  	
    // Is this server an Apache one?
	  if (substr_count(php_sapi_name(), 'apache') < 1) {
	    return false;
	  }
	  
	  $URL = $_SERVER['REQUEST_URI'];
	  $act= "";
	  
	  //echo $URL;
	  
	  $pos = stripos("index.php", $URL);
	  $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
	  $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
	  $_SERVER['PATH_INFO'] = ""; // /contact 
	  $_SERVER['PATH_TRANSLATED'] = "";

	
	  // REQUEST_URI empty?
	  if (empty($URL)) 
	    return false;

	  $_GET = array(); // clear $_GET for no problems
	  	  
	  $REDIRECT = $_SERVER['QUERY_STRING'];
    $section = "";

    switch($REDIRECT) {
    	case 'banned':
	      $section = "banned";
        break;
      default:
        $section = "home";
        break;
    }
	  
	  return $section;	  
  }

  function seo_text($text){

	  $text = preg_replace('/\s/', '_', $text);
	  $text = str_replace('?', '%3F', $text);
	  return $text;

  }
  
  // Do a start link
  function seolink($name, $title=''){
  	global $ext;

	  if (substr_count(php_sapi_name(), 'apache') > 0) {
        
        // decode if is mainsite
        if ($name == "index.php") {
          return $ext->mainsite ."/index.html";
        } else {
          
          // delete de index.php for search what are we doing...
          $name = eregi_replace("index.php", "", $name);
               
          // rest 1 to search ?	  
          $is_oper = substr($name, 0, 1);
          
          // is there a ? then that means whe have ?oper=xxx whatelse
          if ($is_oper == "?") {
          	   
          	// check if there is a &    	
        	  $is_amp = strrpos($name, "&");
        	
        	  // yes, we have an &. So that means there is soemthing more than oper=xxx
            if ($is_amp) {
            	
        	    // yes, there are a &xx=xx
        	    $name = str_replace("?oper=", "", $name);
        	    $rest = $name;
        	    $rest = explode('&', $rest);
        	    $name = $rest[0];
        	    $count = count($rest);
        	    
        	    // check if we are only ordering to execute index.php?oper=xx&act=yy or index.php?oper=xx&order=desc
        	    if ($count == "2") {
        	    	
        	    	// delete the amp; if exists
        	    	$action = str_replace("amp;", "", $rest[1]);
        	    	$action1 = explode('=', $action);
        	    	
        	    	//check if the action is order or act
                if ($action1[0] == "order") {
                	
                  return $ext->mainsite ."/$name/sort_by_{$action1[1]}.html";
                  
                } else {
                	
        	    	  return $ext->mainsite ."/$name/{$action1[1]}.html";
        	    	  
        	    	}
        	      
        	    } else {
        	    	
        	    	// more that one $_GET. index.php?oper=xx&act=yy&otherthing=rr
        	    	$action = explode('=', $rest[1]);

        	    	
        	    	// reading all $_GET values and analyzing which value do we have to add
        	    	$cond = explode('=', $rest[2]);
        	    	$cond = str_replace("amp;", "", $cond);
        	    	
        	    	//print_r($cond);
        	    	//echo "<br /><br />";
        	    	
        	    	// going to check all third &xxx=yyy levels
        	    	
        	    	// is user into PM menu?
        	    	if ($cond[0] == "from")
        	    	  $value1 = "/".$cond[1];
        	    	  
        	    	// reading a pm?
        	    	if ($cond[0] == "pid") {
        	    	  $value2 = $cond[1];
        	    	  $value1 = "";
        	    	}
        	    	// watching a category
        	    	if ($cond[0] == "scatid") {
        	    		$value2 = $cond[1];
        	    	  $value1 = "";
        	      }
        	      
        	      // deleting or editing?
        	    	if ($cond[0] == "nid") {
        	    		$value2 = $cond[1];
        	    	  $value1 = "";
        	      }
        	    	
        	    	// going to check all fourth &xxx=yyy levels
        	    	$cond1 = explode('=', $rest[3]);

        	    	// is user into PM menu?
        	    	if ($cond1[0] == "pmID")
        	    		$value2 = $cond1[1];
        	    	  
        	      if ($title == "") {
        	    	  return $ext->mainsite ."/$name/{$action[1]}/{$value2}{$value1}.html";
        	      } else {
        	      	$title = str_replace(" ", "-", $title);
        	        return $ext->mainsite ."/$name/{$action[1]}/{$value2}{$value1}/$title.html";
        	      }
        	    
        	    }
            
            // no more &. There's only ?oper=xxx
            } else {
        	    
        	    $name = str_replace("?oper=", "", $name);
        	    return $ext->mainsite ."/$name.html";
        	  
      	    }
          }
        
        }
        	  	
		    //return $ext->mainsite ."/" .$this->seo_text($name).".html";

		  
	  } else {
	  	
		  return $name;
		  
	  }
	}
	
	function config() {
 		global $DB, $db_prefix;

		$query = $DB->query("SELECT * FROM {$db_prefix}config");
		while ($row = $DB->fetch_row($query) ) {
			$ckey = $row['ckey'];
			$cvalue = $row['cvalue'];
			$config[$ckey] = $cvalue;
		}		
 		return $config;
 	}
 	
 	function userperms() {
 	   global $vbulletin, $DB, $db_prefix;
 	   
 	   $perms = array();
     
     // Grup de usuario
     $ug = $vbulletin->userinfo['usergroupid'];
     $username = $vbulletin->userinfo['username'];
     $userid = $vbulletin->userinfo['userid'];
     $perms = $vbulletin->usergroupcache[$ug];
     
 	   // ¿Puede administrar?
     if (preg_match("/\,".$ug."\,/i", $this->config['can_enter_admin'])) { $perms['can_admin'] = 1; } else { $perms['can_admin'] = 0; }
     
     // ¿Puede moderar?
     if (preg_match("/\,".$ug."\,/i", $this->config['can_moderate'])) { $perms['can_mod'] = 1; } else { $perms['can_mod'] = 0; }
     
     // Es Superusuario root?
     $perms['is_root'] = 0;
     $query = $DB->query("SELECT rid, userid, username FROM {$db_prefix}roots WHERE userid = '$userid' and username = '$username' ");
     $row = $DB->fetch_row($query);
     if ($row)
       $perms['is_root'] = 1;
 	   
 	   return $perms;
 	}
 	
 	// Decodificamos ciertos carácteres especiales // Ã¡ Ã© Ã­ Ã³ Ãº
 	function UTF8ToEntities($string) {
    /* note: apply htmlspecialchars if desired /before/ applying this function
    /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;
    
    // reject too-short sequences
    $string = preg_replace("/[\302-\375]([\001-\177])/", "&#65533;\\1", $string); 
    $string = preg_replace("/[\340-\375].([\001-\177])/", "&#65533;\\1", $string); 
    $string = preg_replace("/[\360-\375]..([\001-\177])/", "&#65533;\\1", $string); 
    $string = preg_replace("/[\370-\375]...([\001-\177])/", "&#65533;\\1", $string); 
    $string = preg_replace("/[\374-\375]....([\001-\177])/", "&#65533;\\1", $string); 
    
    // reject illegal bytes & sequences
        // 2-byte characters in ASCII range
    $string = preg_replace("/[\300-\301]./", "&#65533;", $string);
        // 4-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/\364[\220-\277]../", "&#65533;", $string);
        // 4-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/[\365-\367].../", "&#65533;", $string);
        // 5-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/[\370-\373]..../", "&#65533;", $string);
        // 6-byte illegal codepoints (RFC 3629)
    $string = preg_replace("/[\374-\375]...../", "&#65533;", $string);
        // undefined bytes
    $string = preg_replace("/[\376-\377]/", "&#65533;", $string); 

    // reject consecutive start-bytes
    $string = preg_replace("/[\302-\364]{2,}/", "&#65533;", $string); 
    
    // decode four byte unicode characters
    $string = preg_replace(
        "/([\360-\364])([\200-\277])([\200-\277])([\200-\277])/e",
        "'&#'.((ord('\\1')&7)<<18 | (ord('\\2')&63)<<12 |" .
        " (ord('\\3')&63)<<6 | (ord('\\4')&63)).';'",
    $string);
    
    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
"'&#'.((ord('\\1')&15)<<12 | (ord('\\2')&63)<<6 | (ord('\\3')&63)).';'",
    $string);
    
    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
    "'&#'.((ord('\\1')&31)<<6 | (ord('\\2')&63)).';'",
    $string);
    
    // reject leftover continuation bytes
    $string = preg_replace("/[\200-\277]/", "&#65533;", $string);
    
    return $string;
  }
  
  // converts quotes ' to a special char, for be able of store it in database
   function convert_quotes($txt) {
   	
   	 $txt = str_replace("'", "&qt;", $txt);
          
     return $txt;
   }
   
   // restores original quote ' from spacial char
   function restore_quotes($txt) {
   	
   	 $txt = str_replace("&qt;", "'", $txt);
          
     return $txt;
   }

 

} // end class

$ext = new ext;


$ext->sitepath = $PATH;                                                     // C:\localhost\htdocs\xampp\damia1\ (old $ext->tpl_sitepath)
                                                                            // /home/mkportal/public_html/maderasmatinez/
$ext->siteurl = $EXT_URL;                                                   // http://localhost/xampp/damia1/index.php
$ext->mainsite = dirname($ext->siteurl);                                    // http://localhost/xampp/damia1


$ext->template = $ext->mainsite."/templates/".$EXT_TEMPLATE;                // http://localhost/xampp/damia1/templates/default/
$ext->images = $ext->mainsite."/templates/".$EXT_TEMPLATE."images/";        // http://localhost/xampp/damia1/templates/default/images/

$ext->config = $ext->config();

$ext->perms = $ext->userperms();

?>